import pymysql
class Mysql(object):
    def __init__(self):
        try:
            self.db = pymysql.connect(host="localhost",user="root",password="123456",database="test")
            self.cursor = self.db.cursor()
            print("连接成功")
        except:
            print("连接失败")
    def getdata(self):
        sql = "select * from user"
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        return results
    def updatedate(self,result):
        sql = "update user set username='%s',password='%s',gender='%s' where id='%s' " % (result['usernames'],result['passwords'],result['genders'],result["ids"])
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
        return "ok"
    def delete(self,id):
        sql = "delete from user where id="+str(id)
        print(sql)
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
    def insert(self,username,password,gender):
        sql = "INSERT INTO user (`username`, `password`, `gender`) VALUES ('%s','%s','%s')" %(username,password,gender)
        print(sql)
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
    def select_usernaem(self,username):
        sql = "select * from user where username = '%s'"%(username)
        print(sql)
        try:
            self.cursor.execute(sql)
            results = self.cursor.fetchall()
            return results
        except:
            return "error"
    def __del__(self):
        self.db.close()